package com.luojialong.aop;

import com.luojialong.enums.AffairStatus;
import com.luojialong.exception.AffairException;
import com.luojialong.model.domain.User;
import com.luojialong.service.UserService;
import com.luojialong.verification.UserPermissionCheck;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PermissionCheckHandle {

    @Resource
    private UserService userService;


    @Around("@annotation(permissionCheck)")
    public Object doHandle(ProceedingJoinPoint joinPoint, UserPermissionCheck permissionCheck) throws Throwable {
        //获得最低权限的用户级别
        int leastRole = permissionCheck.LeastPrivilege();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        User loginUser = userService.getLoginUser(request);

        Integer role = loginUser.getRole();

        if (role == leastRole) {
            throw new AffairException(AffairStatus.NOT_ADMIN,"你没有次权限");
        }
        return joinPoint.proceed();
    }

}
